/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package armazemseujose.model;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

/**
 *
 * @author BRUNA
 */
public class listaCompra {
    
    ArrayList<Compra> compras = new ArrayList();
    private listaItens itens;
    
    public listaCompra() throws FileNotFoundException{
        itens = new listaItens();
        lerArquivoCompra();
    }
    
    public void add(Compra c) throws IOException{
        compras.add(c);
        salvaArquivoCompra(c);
    }
    
    public static void salvaArquivoCompra(Compra c) throws IOException {
        File dir = new File(".");
        File arq = new File(dir, "compras.txt");
        FileWriter fileWriter = new FileWriter(arq, true);
        PrintWriter printWriter = new PrintWriter(fileWriter);
        printWriter.println(c.getItem().getNome() + "|" + c.getQuantidade() + "|" + c.getPrecoTotal());
        printWriter.flush();

    }
    
     public void lerArquivoCompra() throws FileNotFoundException {
        Scanner scanner = new Scanner(new FileReader("compras.txt"))
                .useDelimiter("\\||\\n");
        while (scanner.hasNext()) {
            String nomeItem = scanner.next();
            String quantidade = scanner.next();
            String preco = scanner.next();
            String precoTotal = preco.substring(0, preco.length() - 1);
            double i = Double.parseDouble(precoTotal);
            int j = Integer.parseInt(quantidade);
            Item item = itens.procuraItem(nomeItem);
            compras.add(new Compra(item, j, i));
        }
    }
     
    public double calculaTotalCompras(){
        double total = 0;
        for(Compra i : compras){
            total = total + i.getPrecoTotal();
        }
        return total;
    }
    
}
